package com.jtech.together.mvp.presenter;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;

import com.jtech.together.manager.UserManager;
import com.jtech.together.model.UserModel;
import com.jtech.together.mvp.contract.ProfileCompleteContract;
import com.jtech.together.util.BmobUtil;

import java.io.File;

import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;

/**
 * 用户信息完善页面
 * Created by wuxubaiyang on 2017/5/10.
 */
public class ProfileCompletePresenter implements ProfileCompleteContract.Presenter {
    private Context context;
    private ProfileCompleteContract.View view;

    public ProfileCompletePresenter(Context context, ProfileCompleteContract.View view, Bundle bundle) {
        this.context = context;
        this.view = view;
    }

    @Override
    public void modifyProfile(String avatarUrl, final String nickName, final String bio, final int sex, final long birthday) {
        if (avatarUrl.startsWith("http://") || avatarUrl.startsWith("https://")) {
            updateProfile(avatarUrl, nickName, bio, sex, birthday);
        } else {
            //非http开头代表头像还未上传，则需要先上传文件再更新用户信息
            final BmobFile bmobFile = new BmobFile(new File(avatarUrl));
            bmobFile.uploadblock(new UploadFileListener() {
                @Override
                public void done(BmobException e) {
                    if (null == e) {
                        String avatarUrl = bmobFile.getFileUrl();
                        view.avatarUpdateSuccess(avatarUrl);
                        //更新用户信息
                        updateProfile(avatarUrl, nickName, bio, sex, birthday);
                    } else {
                        view.modifyFail("头像上传失败，请重试");
                    }
                }

                @Override
                public void onProgress(Integer value) {
                    Log.i("avatarUploadProgress：", value + "");
                }
            });
        }
    }

    /**
     * 更新用户信息
     *
     * @param avatarUrl
     * @param nickName
     * @param sex
     * @param birthday
     */
    private void updateProfile(String avatarUrl, String nickName, String bio, int sex, long birthday) {
        UserModel userModel = UserManager.getCurrentUser();
        userModel.setAvatar(avatarUrl);
        userModel.setNickname(nickName);
        userModel.setBio(bio);
        userModel.setSex(sex);
        userModel.setBirthday(birthday);
        userModel.update(new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (null == e) {
                    view.modifySuccess();
                } else {
                    view.modifyFail(BmobUtil.getErrorMessage(e.getErrorCode()));
                }
            }
        });
    }
}